import roleService from '../service/role'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';

const router = useRouter()

export interface queryRole {
    id?: number,
    name?: string
}

interface IRoleAction {
    getRoleList: (callback: any) => void
    getById: (id: number, callback: any) => void
    addRole: (name: string, callback: any) => void
    updateRole: (obj: queryRole, callback: any) => void
    deleteRole: (id: number, callback: any) => void
}

export function roleHook(): IRoleAction {

    // 获取角色列表
    function getRoleList(callback: any) {
        roleService.getRoleList().then((res: any) => {
            if (res.data.code == 0) {
                // console.log(res.data.data)
                callback(res.data.data)
            } else {
                ElMessage(res.data.msg)
            }
        }).catch(() => {
            ElMessage.error("请求失败")
        })
    }

    // 添加角色
    function addRole(name: string, callback: any) {
        roleService.addRole(name).then((res: any) => {
            if (res.data.code == 0) {
                ElMessage({ type: "success", message: res.data.msg })
                getRoleList(callback)
            } else {
                ElMessage(res.data.msg)
            }
        }).catch(() => {
            ElMessage.error("请求失败")
        })
    }

    // 角色回显
    function getById(id: number, callback: any) {
        roleService.getRoleById(id).then((res: any) => {
            if (res.data.code == 0) {
                callback(res.data.data)
            } else {
                ElMessage(res.data.msg)
            }
        }).catch(() => {
            ElMessage.error("请求失败")
        })
    }

    // 修改角色
    function updateRole(obj: queryRole, callback: any) {
        roleService.updateRole(obj).then((res: any) => {
            if (res.data.code == 0) {
                ElMessage({ type: "success", message: res.data.msg })
                getRoleList(callback)
            } else {
                ElMessage(res.data.msg)
            }
        }).catch(() => {
            ElMessage.error("请求失败")
        })
    }

    // 删除角色
    function deleteRole(id: number, callback: any) {
        roleService.deleteRole(id).then((res: any) => {
            if (res.data.code == 0) {
                ElMessage({ type: "success", message: res.data.msg })
                getRoleList(callback)
            } else {
                ElMessage(res.data.msg)
            }
        }).catch(() => {
            ElMessage.error("请求失败")
        })
    }

    return {
        getRoleList,
        getById,
        addRole,
        deleteRole,
        updateRole,
    }
}